﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
using TKToXML.Persistence;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NHibernate;
using TKToXML.Persistence.Repositories;
using TKToXML.Models;

namespace TKToXML
{
    public partial class Form1 : Form
    {
        public string Form_Reference;
        protected ISession session;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            //string test = "";
            //for (var i = 1; i <= 10; i++)
            //{
            //    test = test + "{" + System.Guid.NewGuid().ToString() + "}";

            //}
            //EDTOKHAI.WriteFile(@"e:\guid.text", test);

            Request request;
            EDTOKHAI tokhai;
            using (var context = new ECUSTOMSEntities())
            {
                tokhai = context.EDTOKHAIs.Where(tk => tk.So_CT == 1 && tk.Nam_CT == 1).First();
                //Cần phải đặt reference cho request để còn dùng sau này khi hỏi trạng thái                

                tokhai.Reference = System.Guid.NewGuid().ToString();
                tokhai.Function = (int)MessageFuntion.KhaiBao;
                tokhai.TongChiPhiKhac = 0;
                tokhai.PhiVanTai = 0;
                tokhai.PhuongPhapXacDinhTriGia = 1;
                tokhai.CacKhoanCongTruCacKhoanTru = 0;

                tokhai.MaLoaiGiaTriDieuChinh = 1;
                tokhai.PhanTramDieuChinh = 10;
                tokhai.SoTienDieuChinh = 0;

                Form_Reference = tokhai.Reference;

                request = new Request()
                {
                    MaDV = "0100101308",
                    MaHQ = tokhai.MaHQ,
                    Type = MessageType.CommercialImportDeclaration.ToString("d"),
                    Function = MessageFuntion.KhaiBao.ToString("d"),
                    MessageId = System.Guid.NewGuid().ToString(),
                    Reference = tokhai.Reference
                };

                //VanDon vanDon = new VanDon
                //{
                //    //Agent = new Agent { Identity = "0100100008", Name = "Cong ty may 10", Status = 1 },
                //    CangDich = "HCM", //Ten_CA_GH
                //    CangDoHang = "Cat Lai", //Ten_CA_DH
                //    CangXepHang = "New York", //Ten_CA_XH
                //    //CustomsReference = 11,
                //    //DeclarationDocument = new DeclarationDocument { MaHQ = "A01B", MaLH = "NKD01", NgayTK = new DateTime(2012, 08, 10) },
                //    //Function = MessageFuntion.KhaiBao.ToString("d"),
                //    //Importer = new Importer { Identity = "0100100008", Name = "Cong ty may 10" },
                //    //IssueDate = new DateTime(2012, 08, 10),
                //    //MaHQ = "A01B",
                //    MaNuocPhatHanhVanDon = "VN", //Chua thay co trong database cua anh Thanh
                //    NgayKhoiHanh = new DateTime(2012, 08, 10), //Ngay_KH
                //    //NgayNhanSoTiepNhan = new DateTime(2012, 08, 10),
                //    NgayPhuongTienDen = new DateTime(2012, 08, 10), //Ngay_DE
                //    NgayPhuongTienDi = new DateTime(2012, 08, 10), //Ngay_KH ???
                //    NgayVanDon = new DateTime(2012, 08, 10), //Ngay_VD
                //    QuocTichPTVT = "US", //QuocTich_PTVT
                //    //Reference = Guid.NewGuid().ToString(),
                //    SoHieuChuyenDi = "123",
                //    SoVanDon = "123", //So_VD
                //    TenHangVanTai = "123",
                //    TenNguoiDuocThongBao = "Cong ty abc",
                //    TenNguoiGuiHang = "Cong ty def",
                //    TenNguoiNhanHang = "Cong ty abc",
                //    TenPhuongTienVanTai = "Tau abc", //Ten_PTVT
                //    TongSoKien = 123, //Tong_SK
                //    //Type = "704"
                //};
                var vanDonRepository = new VanDonRepository(session);
                VanDon vanDon = vanDonRepository.GetAll().First();
                //Mot so thong tin khong co trong database cua a Thanh
                vanDon.MaNuocPhatHanhVanDon = "VN";
                vanDon.NgayPhuongTienDi = vanDon.NgayKhoiHanh;
                vanDon.SoHieuChuyenDi = "123";
                vanDon.TenHangVanTai = "123";
                vanDon.TenNguoiDuocThongBao = "Cong ty abc";
                vanDon.TenNguoiGuiHang = "Cong ty def";
                vanDon.TenNguoiNhanHang = "Cong ty abc";

                //Hop dong                
                var hopDongChiTietRepository = new HopDongChiTietRepository(session);
                List<HopDongChiTiet> hopDongChiTiets = hopDongChiTietRepository.GetAll().ToList();
                string hopDongChiTietXML = "";
                foreach (var hopDongChiTiet in hopDongChiTiets)
                    hopDongChiTietXML += hopDongChiTiet.ToXML();

                var hopDongRepository = new HopDongRepository(session);
                var hopDong = hopDongRepository.GetAll().First();
                string hopDongXML = hopDong.ToXML();
                hopDongXML = hopDongXML.Insert(hopDongXML.IndexOf("</ContractDocument>"), hopDongChiTietXML);

                //Hoa don
                //TODO: Chuan bi lam sang mang hoa don 0302345441

                //nội dung tờ khai
                string content = "";
                //Insert nội dung vận đơn vào tờ khai
                content = tokhai.ToXML().Insert(tokhai.ToXML().IndexOf("</Declaration>"), vanDon.ToXML());
                //Insert nội dung hợp đồng vào tờ khai
                content = content.Insert(content.IndexOf("</Declaration>"), hopDongXML);

                //Insert nội dung tờ khai vào request
                string result = request.ToXML().Insert(request.ToXML().IndexOf("</Content>"), content);
                //Ghi nội dung message sẽ gửi đi ra file
                EDTOKHAI.WriteFile(@"c:\tokhai123.xml", result);

                //Tiến hành gửi đi
                //password là chuỗi md5 lấy trong database tntt_msg2
                CisService.CISService test = new CisService.CISService();
                result = test.Send(result, "0100101308", "66406bc4c790949aa98d07a4f79ad704");
                result = result.Substring(result.IndexOf("<Content>") + "<Content>".Length);
                result = result.Substring(0, result.IndexOf("</Content>"));
                textBox1.Text = result;
            }

            //MessageBox.Show(MessageFuntion.KhaiBao.ToString("d"));

            //MessageBox.Show(DateTime.Now.ToLongDateString() + Environment.NewLine +
            //    DateTime.Now.ToShortDateString());
            //MessageBox.Show(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

        }

        private void btnRequest_Click(object sender, EventArgs e)
        {
            CisService.CISService test = new CisService.CISService();
            var request = new Request()
            {
                MaDV = "0100101308",
                MaHQ = "T01E01",
                Type = MessageType.CommercialImportDeclaration.ToString("d"),
                Function = MessageFuntion.HoiTrangThai.ToString("d"),
                MessageId = System.Guid.NewGuid().ToString(),
                Reference = Form_Reference
            };
            var requestForStatus = new RequestForStatus()
            {
                MaDV = "0100101308",
                Type = MessageType.CommercialImportDeclaration.ToString("d"),
                Reference = Form_Reference,
                StatusDV = 3
            };


            string result = request.ToXML().Insert(request.ToXML().IndexOf("</Content>"), requestForStatus.ToXML());
            EDTOKHAI.WriteFile(@"e:\request.xml", result);
            //password là chuỗi md5 lấy trong database tntt_msg2
            result = test.Send(result, "0100101308", "66406bc4c790949aa98d07a4f79ad704");
            result = result.Substring(result.IndexOf("<Content>") + "<Content>".Length);
            result = result.Substring(0, result.IndexOf("</Content>"));
            textBox1.Text = result;
        }

        static public string EncodeTo64(string toEncode)
        {

            byte[] toEncodeAsBytes

                  = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);

            string returnValue

                  = System.Convert.ToBase64String(toEncodeAsBytes);

            return returnValue;

        }

        static public string DecodeFrom64(string encodedData)
        {

            byte[] encodedDataAsBytes

                = System.Convert.FromBase64String(encodedData);

            string returnValue =

               //System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
            System.Text.UTF8Encoding.Unicode.GetString(encodedDataAsBytes);

            return returnValue;

        }

        private void btnTestSend_Click(object sender, EventArgs e)
        {
            //Hủy khai báo
            var huyKhaiBao = new HuyKhaiBao
            {
                Content = "Thích hủy",
                CustomsReference = 123,
                Function = MessageFuntion.KhaiBao.ToString(),
                IssueDate = System.DateTime.Now,
                MaHQ = "T01E01",
                NgayNhanSoTiepNhan = System.DateTime.Now,
                Reference = "0a62bf59-011d-4420-b9e2-8b2772b586ec",
                Statement = 01,
                Type = "501"
            };

            CisService.CISService test = new CisService.CISService();
            StreamReader reader = new StreamReader(@"e:\1.xml");

            string result = test.Send(reader.ReadToEnd(), "0100101308", "66406bc4c790949aa98d07a4f79ad704");

            textBox1.Text = result;
            //XMLValidator.Validate(@"e:\1.xml", @"E:\work\AnhHieu\TKToXML\TKToXML\ToKhaiNKD.xsd");
        }

        private void btnTestRequest_Click(object sender, EventArgs e)
        {
            CisService.CISService test = new CisService.CISService();

        }

        private void button1_Click(object sender, EventArgs e)
        {
           

            VanDon vanDon = new VanDon
            {
                //Agent = new Agent { Identity = "0100100008", Name = "Cong ty may 10", Status = 1 },
                CangDich = "HCM", //Ten_CA_GH
                CangDoHang = "Cat Lai", //Ten_CA_DH
                CangXepHang = "New York", //Ten_CA_XH
                //CustomsReference = 11,
                //DeclarationDocument = new DeclarationDocument { MaHQ = "A01B", MaLH = "NKD01", NgayTK = new DateTime(2012, 08, 10) },
                //Function = MessageFuntion.KhaiBao.ToString("d"),
                //Importer = new Importer { Identity = "0100100008", Name = "Cong ty may 10" },
                //IssueDate = new DateTime(2012, 08, 10),
                //MaHQ = "A01B",
                MaNuocPhatHanhVanDon = "VN", //Chua thay co trong database cua anh Thanh
                NgayKhoiHanh = new DateTime(2012, 08, 10), //Ngay_KH
                //NgayNhanSoTiepNhan = new DateTime(2012, 08, 10),
                NgayPhuongTienDen = new DateTime(2012, 08, 10), //Ngay_DE
                NgayPhuongTienDi = new DateTime(2012, 08, 10), //Ngay_KH ???
                NgayVanDon = new DateTime(2012, 08, 10), //Ngay_VD
                QuocTichPTVT = "US", //QuocTich_PTVT
                //Reference = Guid.NewGuid().ToString(),
                SoHieuChuyenDi = "123",
                SoVanDon = "123", //So_VD
                TenHangVanTai = "123",
                TenNguoiDuocThongBao = "Cong ty abc",
                TenNguoiGuiHang = "Cong ty def",
                TenNguoiNhanHang = "Cong ty abc",
                TenPhuongTienVanTai = "Tau abc", //Ten_PTVT
                TongSoKien = 123, //Tong_SK
                //Type = "704"
            };
            textBox1.Text = vanDon.ToXML();
            EDTOKHAI.WriteFile(@"e:\vandon.xml", vanDon.ToXML());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            setup();
        }

        public void setup()
        {
            NHibernateConfiguration.Initialize("TestEcustoms", RebuildDatabase());
            session = NHibernateConfiguration.CreateAndOpenSession();
        }

        private Action<Configuration> RebuildDatabase()
        {
            //return config => new SchemaExport(config).Create(false, true);
            return config => new SchemaUpdate(config).Execute(false, true);
        }
    }
}
